package com.zbb.order.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class DelayedQueueConfig {
 public static final String DELAYED_QUEUE_NAME = "delayed.queue";
 public static final String DELAYED_EXCHANGE_NAME = "delayed.exchange";
 public static final String DELAYED_ROUTING_KEY = "delayed.routingkey";

 //死信交换机，队列，路由相关配置
 public static final String DLK_EXCHANGE = "dlk.exchange";
 public static final String DLK_ROUTEKEY = "dlk.routeKey";
 public static final String DLK_QUEUE = "dlk.queue";


 @Bean
 public Queue delayQueue() {
  Map<String, Object> args = new HashMap<>();
  args.put("x-dead-letter-exchange", DLK_EXCHANGE);
  args.put("x-dead-letter-routing-key", DLK_QUEUE);
  return new Queue(DELAYED_QUEUE_NAME, true, false, false, args);
 }

 @Bean
 public Queue deadLetterQueue() {
  return new Queue(DLK_QUEUE, true, false, false);
 }
 @Bean
 public TopicExchange deadLetterExchange() {
  return new TopicExchange(DLK_EXCHANGE);
 }

 //自定义交换机 我们在这里定义的是一个延迟交换机
 @Bean
 public CustomExchange delayedExchange() {
 Map<String, Object> args = new HashMap<>();
 //自定义交换机的类型
 args.put("x-delayed-type", "direct");
 return new CustomExchange(DELAYED_EXCHANGE_NAME, "x-delayed-message", true, false, args);
 }

 @Bean
 public Binding deadLetterBinding(
         @Qualifier("deadLetterQueue") Queue queue,
         @Qualifier("deadLetterExchange") TopicExchange deadExchange) {
  return BindingBuilder.bind(queue).to(deadExchange).with(DLK_QUEUE);
 }

 @Bean
 public Binding bindingDelayedQueue(@Qualifier("delayQueue") Queue queue,
                                    @Qualifier("delayedExchange") CustomExchange delayedExchange) {
 return BindingBuilder.bind(queue).to(delayedExchange).with(DELAYED_ROUTING_KEY).noargs();
 }
}
